import json
import os
import socket
import time
from ctypes import *
from ftplib import FTP

from urllib.parse import unquote
from django.core import serializers
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from django.views.decorators.http import require_http_methods
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.response import Response
from rest_framework import status
from .serializers import FileSerializers
from dwebsocket.decorators import accept_websocket, require_websocket
from django.utils.deprecation import MiddlewareMixin

from .getContain.shoes import get_start
from .models import Book


@require_http_methods(["GET"])
def add_book(request):
    response = {}
    try:
        book = Book(book_name=request.GET.get('book_name'))
        book.save()
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)


@accept_websocket
def test_websocket(request):
    if request.is_websocket():
        while 1:
            time.sleep(1)
            dit = {
                'time': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            }
            request.websocket.send(json.dumps(dit))


@accept_websocket
def console_socket(request):
    if request.is_websocket():
        request.websocket.send(json.dumps({'code': 40001, 'message': '连接成功'}))
        try:
            while 1:
                message = request.websocket.wait()
                if message:
                    print(bytes.decode(message))
        except Exception as e:
            print(e)
            request.websocket.close()


@accept_websocket
def model_container_socket(request):
    if request.is_websocket():
        request.websocket.send(json.dumps({'code': 40001, 'message': '连接成功'}))
        try:
            while 1:
                message = request.websocket.wait()
                if message:
                    if bytes.decode(message) == 'show':
                        points = []
                        file = open('./example/points.json', 'r')
                        for line in file.readlines():
                            points_line = json.loads(line)
                            for p in points_line:
                                points.append(p)
                        string = json.dumps(points)
                        file.close()
                        request.websocket.send(json.dumps({
                            'code': 40002,
                            'message': string,
                        }))
        except Exception as e:
            print(e)
            request.websocket.close()


@require_http_methods(["GET"])
def show_book(request):
    response = {}
    try:
        books = Book.objects.filter()
        response['list'] = json.loads(serializers.serialize("json", books))
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)


@require_http_methods(["POST"])
def upload_file(request):
    myFile = request.FILES.get('file')
    if not myFile:
        return HttpResponse("No files for upload")
    destination = open(os.path.join('./', myFile.name), 'wb+')
    for chunk in myFile.chunks():
        destination.write(chunk)
    destination.close()
    return HttpResponse("Upload success")


@require_http_methods(["GET"])
def get_running_info(request):
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)
    config = {
        'local_hostname': hostname,
        'local_ip': ip,
    }
    with open('./global_config/network.json', "w+") as file:
        file.write(json.dumps(config))

    return HttpResponse(json.dumps(config))


class FileView(APIView):
    parser_classes = (MultiPartParser, FormParser)

    def post(self, request, *args, **kwargs):

        file_serializer = FileSerializers(data=request.data)
        if file_serializer.is_valid():
            file_serializer.save()
            file = os.path.abspath('.') + unquote(file_serializer.data['file'])  # url转中文
            get_start(file)
            return Response(file_serializer.data, status=status.HTTP_201_CREATED)

        else:
            return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)







